package org.edu.modules.oa.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.entity.*;
import org.edu.modules.oa.mapper.IVeOaNewsMapper;
import org.edu.modules.oa.service.IVeOaCarInfoService;
import org.edu.modules.oa.service.IVeOaNewsService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.VeOaCarWeihuVo;
import org.edu.modules.oa.vo.VeOaNewsExportVo;
import org.edu.modules.oa.vo.VeOaNewsVo;
import org.edu.modules.oa.vo.VeOaNoticeExportVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "新闻资讯管理")
@RestController
@RequestMapping("oa/veOaNews")
@Slf4j
@ApiSort(value = 100)
public class VeOaNewsController {
    @Resource
    private IVeOaNewsMapper iVeOaNewsMapper;
    @Resource()
    private IVeOaNewsService iVeOaNewsService;// 新闻业务类
    @Resource
    private OSS ossClient;
    @Autowired
    private RedisUtil redisUtil; // redis服务类

    // 增加公告信息
    @AutoLog(value = "新闻资讯管理-增加新闻")
    @ApiOperation(value = "增加新闻", notes = "新闻资讯管理-增加新闻")
    @PostMapping(value = "/addNews")
    public Result addNews(MultipartFile file, VeOaNewsEntity veOaNewsEntity) throws Exception {


        //创建文件类
        VeFileFilesEntity veFileFilesEntity = null;
        String fileName = null;
        String suffixName = null;
        if (file != null) {
            //把MultipartFile文件流转换成文件
            File document = null;
            //获取文件名
            fileName = file.getOriginalFilename();
            //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
            String[] arr = fileName.split("\\.");
            //获取文件后缀名
            suffixName = arr[arr.length - 1];
            if (suffixName.equals("java") || suffixName.equals("class")) {
                return Result.error(400, "文件类型不能上传");
            }
            try {
                String originalFilename = file.getOriginalFilename();
                String[] filename = originalFilename.split("\\.");
                document = File.createTempFile(filename[0], filename[1]);
                file.transferTo(document);
                document.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件长度
            Long size = file.getSize();
            //获取唯一的文件名称
            String docName = UUID.randomUUID().toString();
            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
//            PutObjectResult result = ossClient.putObject("digital-school-xx0422", "school-demo/" + docName, document);
            PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
            //文件下载地址
//            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/" + docName;
            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/" + fileName;
            veFileFilesEntity = new VeFileFilesEntity();
            //当前插入的时间
            Long time = System.currentTimeMillis() / 1000;
            veFileFilesEntity.setSourceFile("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
            veFileFilesEntity.setName(fileName);
            veFileFilesEntity.setExt(suffixName);
            veFileFilesEntity.setCreateTime(time);
            veFileFilesEntity.setSize(size);
        }
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println(user);
        veOaNewsEntity.setCreateBy(user.getRealname());
        veOaNewsEntity.setDeptId((long) 0);

        veOaNewsEntity.setIsDeleted(0);
        veOaNewsEntity.setTerminalId(0);
        int result = iVeOaNewsService.addNews(veOaNewsEntity, veFileFilesEntity);

        return Result.OK(result);
    }

    // 修改公告信息
    @AutoLog(value = "新闻资讯-修改公告")
    @ApiOperation(value = "修改新闻", notes = "新闻资讯-修改公告")
    @PostMapping(value = "/amendNews")
    public Result amendNews(MultipartFile file, VeOaNewsEntity veOaNewsEntity) throws Exception {

        //创建文件类
        VeFileFilesEntity veFileFilesEntity = null;
        String fileName = null;
        String suffixName = null;
        if (file != null) {
            //把MultipartFile文件流转换成文件
            File document = null;
            //获取文件名
            fileName = file.getOriginalFilename();
            //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
            String[] arr = fileName.split("\\.");
            //获取文件后缀名
            suffixName = arr[arr.length - 1];
            if (suffixName.equals("java") || suffixName.equals("class")) {
                return Result.error(400, "文件类型不能上传");
            }
            try {
                String originalFilename = file.getOriginalFilename();
                String[] filename = originalFilename.split("\\.");
                document = File.createTempFile(filename[0], filename[1]);
                file.transferTo(document);
                document.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件长度
            Long size = file.getSize();
            //获取唯一的文件名称
            String docName = UUID.randomUUID().toString();
            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
//            PutObjectResult result = ossClient.putObject("digital-school-xx0422", "school-demo/" + docName, document);
            PutObjectResult result = ossClient.putObject("exaplebucket-beijing", docName+"/"+fileName, document);
            //文件下载地址
//            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/" + docName;
            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/" + fileName;
            veFileFilesEntity = new VeFileFilesEntity();
            //当前插入的时间
            Long time = System.currentTimeMillis() / 1000;
            veFileFilesEntity.setSourceFile("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
            veFileFilesEntity.setName(fileName);
            veFileFilesEntity.setExt(suffixName);
            veFileFilesEntity.setCreateTime(time);
            veFileFilesEntity.setSize(size);
        }
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println(user);
        veOaNewsEntity.setCreateBy(user.getRealname());
        veOaNewsEntity.setDeptId((long) 0);
        int result = 0;
        try {
            result = iVeOaNewsService.amendNews(veOaNewsEntity, veFileFilesEntity);
        } catch (Exception e) {
            return Result.error(500, "表格数据有问题不能上传");
        }
        return Result.OK(result);
    }


    @AutoLog(value = "新闻资讯-初始化下拉框")
    @ApiOperation(value = "初始化下拉框", notes = "新闻资讯-初始化下拉框")
    @PostMapping(value = "/getBox")
    public Result<?> getBox() {
        List arr = iVeOaNewsMapper.getCreateBy();
        List arr2 = iVeOaNewsMapper.getTitleStr();
        HashMap<String, Object> map = new HashMap<>();
        map.put("createByArr", arr);
        map.put("titleStrArr", arr2);
        return Result.OK(map);

    }

    @AutoLog(value = "新闻资讯-显示表格")
    @ApiOperation(value = "显示表格", notes = "新闻资讯-显示表格")
    @PostMapping(value = "/showTable")
    public Result<?> showTable(Integer startPage, Integer pageSize, VeOaNewsEntity veOaNewsEntity) {
        System.out.println(startPage + " " + pageSize);
        System.out.println(veOaNewsEntity);
        HashMap<String, Object> map = iVeOaNewsService.showTable(startPage, pageSize, veOaNewsEntity);
        // 获取redis存的用户值


        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        map.put("userName", user.getRealname());
        return Result.OK(map);
    }

    @AutoLog(value = "新闻资讯-单个删除")
    @ApiOperation(value = "单个删除", notes = "新闻资讯-单个删除")
    @PostMapping(value = "/oneDelete")
    public Result<?> oneDelete(Integer id) {
        Integer result = iVeOaNewsService.deleteRecord((long) id);
        return Result.OK(result);
    }

    @AutoLog(value = "新闻资讯-批量删除")
    @ApiOperation(value = "批量删除", notes = "新闻资讯-批量删除")
    @PostMapping(value = "/allDelete")
    public Result<?> allDelete(String idStr) {
//        System.out.println("zhanchu"+idStr);
        Integer result = 0;
        String data[] = idStr.split(",");

        for (int i = 1; i < data.length; i++) {

            result += iVeOaNewsService.deleteRecord(Long.parseLong(data[i]));

        }
        return Result.OK();
    }

    //导出
    @AutoLog(value = "新闻资讯-导出excel表格")
    @ApiOperation(value = "导出excel表格", notes = "新闻资讯-导出excel表格")
    @RequestMapping(value = "/exportNewsTable")
    public ModelAndView exportTable() {
        VeOaNewsEntity veOaNewsEntity = new VeOaNewsEntity();

        //创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //查数据获得维护表格的集合
        List<VeOaNewsExportVo> list = iVeOaNewsService.export(veOaNewsEntity);
        //文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "新闻信息");
        //数据的类型
        mv.addObject(NormalExcelConstants.CLASS, VeOaNewsExportVo.class);
        //获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("新闻资讯信息", "导出人:" + user.getRealname(), "导出新闻资讯信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    //导入
    @AutoLog(value = "新闻资讯-导入")
    @ApiOperation(value = "导入", notes = "新闻资讯-导入")
    @PostMapping(value = "/importExcel")
    public Result<?> importExcel(HttpServletRequest req, HttpServletResponse resp) {
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //取出来
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                //上传的数据的集合(list就是文件里所有内容)
                List<VeOaNewsExportVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaNewsExportVo.class, params);
                System.out.println("================" + list.size() + "================");
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //加入数据库使用的集合
                List<VeOaNewsEntity> entityList = new ArrayList<>();
                //循环遍历把需要的字段拷贝到数据库插入的集合中
                for (VeOaNewsExportVo v : list) {
                    System.out.println("=============================");
                    System.out.println(v);
                    System.out.println("=============================");
                    VeOaNewsEntity veOaNewsEntity = new VeOaNewsEntity();
                    veOaNewsEntity.setIsDeleted(0);
                    veOaNewsEntity.setContent(v.getContent());
                    veOaNewsEntity.setCreateBy(v.getCreateBy());
                    veOaNewsEntity.setDeptId((long) 0);
                    veOaNewsEntity.setReaders(v.getReaders());
                    veOaNewsEntity.setTitleStr(v.getTitleStr());
                    veOaNewsEntity.setTerminalId(0);

                    entityList.add(veOaNewsEntity);
                }
                iVeOaNewsService.saveBatch(entityList);
                return Result.ok("文件导入成功！数据行数：" + entityList.size());
            } catch (Exception e) {
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    @AutoLog(value = "新闻资讯-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "新闻资讯-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("OA问题文档(1).docx");
        result.success(url);
        return result;
    }
}
